import {
    login,
    getUserInfo,
    logout
} from '@/api/user'

import {
    getToken,
    setToken,
    setExpiresIn,
    removeToken
} from '@/utils/auth'

const state = {
    token: getToken(),
    userId: '',
    username: '',
    role: ''
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token;
    },

    SET_EXPIRES_IN: (state, time) => {
        state.expires_in = time;
    },

    SET_USERID: (state, userId) => {
        state.userId = userId
    },

    SET_USERNAME: (state, username) => {
        state.username = username
    },

    SET_ROLE: (state, role) => {
        state.role = role
    }
}

const actions = {
    // 登录API
    Login({ commit }, userInfo) {
        const userCard = userInfo.userCard.trim()
        const password = userInfo.password
        return new Promise((resolve, reject) => {
            login(userCard, password).then(res => {
                let data = res.data

                setToken(data.access_token)
                commit('SET_TOKEN', data.access_token)

                setExpiresIn(data.expires_in)
                commit('SET_EXPIRES_IN', data.expires_in)

                resolve()
            }).catch(err => {
                reject(err)
            })
        })
    },

    // 获取登录用户的信息
    GetUserInfo({ commit }) {
        return new Promise((resolve, reject) => {
            getUserInfo().then(res => {
                const user = res.data
                const userId = user.userId
                const username = user.username
                const role = user.role
                commit('SET_USERID', userId)
                commit('SET_USERNAME', username)
                commit('SET_ROLE', role)
                resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    },

    // 退出登录
    Logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                commit('SET_TOKEN', '')
                commit('SET_EXPIRES_IN', '')
                commit('SET_USERID', '')
                commit('SET_USERNAME', '')
                commit('SET_ROLE', '')
                removeToken()
                resolve()
            }).catch(err => {
                reject(err)
            })
        })
    }
}

const getters = {};

export default {
    state,
    mutations,
    actions,
    getters
}
